package com.naiterui.ehp.bs.weixin.service.impl;

import com.naiterui.ehp.bp.support.exception.BusinessException;
import com.naiterui.ehp.bs.weixin.constant.WeixinConstant;
import com.naiterui.ehp.bs.weixin.properties.WeixinProperties;
import com.naiterui.ehp.bs.weixin.service.UserService;
import com.naiterui.ehp.bs.weixin.service.WechatService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.util.crypto.SHA1;
import me.chanjar.weixin.mp.api.WxMpService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

/**
 * @author gaoliangliang
 * @date 2019/11/25 9:08 下午
 * @since 1.0.0
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class WechatServiceImpl implements WechatService {

    @Value("${ehp.storage.qrcode:''}")
    private String ehpDomainFile;
    private final String QRCODE_TASK_PREFIX = "QRCODE_TASK_PREFIX_";


    private final UserService customerService;
    private final WeixinProperties weixinProperties;

    @Async
    @Override
    public void scan(String openId, String eventKey, WxMpService wxMpService) throws WxErrorException, BusinessException {

        //普通关注
        if (StringUtils.isEmpty(eventKey)) {
            customerService.mpRegister(openId, eventKey, wxMpService);
            return;
        }

        if (eventKey.startsWith(WeixinConstant.QR_CODE_DEFAULT_PREFIX)) {
            eventKey = eventKey.replace(WeixinConstant.QR_CODE_DEFAULT_PREFIX, "");
        }

    }

    @Override
    public void subscribe(String openId, String eventKey, WxMpService wxMpService) throws WxErrorException, BusinessException {
        this.scan(openId, eventKey, wxMpService);
    }

    @Async
    @Override
    public void unsubscribe(String openId, WxMpService wxMpService) throws WxErrorException {
        customerService.mpUnsubscribe(openId, wxMpService);
    }

    @Override
    public void menuClick(String openId, String eventKey, WxMpService weixinService) throws WxErrorException {
    }

    @Override
    public String checkToken(String signature, String timestamp, String nonce, String echostr) {
        String token = weixinProperties.getToken();
        String configSign = SHA1.gen(token, timestamp, nonce);
        if (configSign.equals(signature)) {
            log.info("token校验通过，signature：{}；timestamp：{}；nonce：{}；echostr：{}；", signature, timestamp, nonce, echostr);
            return echostr;
        }
        log.info("token校验失败，signature：{}；timestamp：{}；nonce：{}；echostr：{}；", signature, timestamp, nonce, echostr);
        return "FILED";
    }

}
